import 'dart:async';
import 'dart:math';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:uverify/uverify.dart';
import 'package:flutter/cupertino.dart';

class UmengConfig {
  // static String appKey = "5f97bc961c520d307399d07d";
  // static String appSecret =
  //     "PCR+lMkDTcQ808Pmg/RiHRA8eHkPXh+yj19HCFp3909pc/REeFa2REz9UYxkGJstrN5YOARzjJU/c3XNwe2dZw0TKEswL37GAdGEMQ3zUJJnLZTRh+DX5w2lw9ycaP7dVsVgou+FTYWYOkn53ntyRigKTKlL4C8pBBXYDllAl5wl/5tBUo2xMrKkq6wRfXX74qJiw0xw5Ebd4fXx/Ri6pNFYS7P3RTx7xl3be+rlYsuGp8vM8IO1thRMwW4tLZD028HAcJ+nP2bApanzWosYO8O7pZcbemrw9VqKM2/URzAB29yEARBvSTRxuxuGwu/r";
  static String appKey = "5f506281a4aebb6a2feadb05";
  static String appSecret =
      "qZt4oEAuTfUDmjW82bcvS2VGYL6NLkTFvnfqY5uX862K8hi0xVf5PMH5K5k71qXwjfsRJwLPoinmaPvtcVO51lCi0exM9cuOuPA9NvgTJdhihOQo7xuSpim4WZjul07j8GcViq9Gi4V3QYCEO59XFav8qR75DsLRoEFVD0Q83cDD6UN8GMd7LDXI71h2pl7+/9giExVGqgimhrlzO7p9JuM8ZwSxrCTVMAf9jmBXwpx14pihFbtZkJJQzauP1HDXEXTlkfuY9c9j3P6KB4q2Kkfwdh0TmaXx";
}

Map<String, dynamic> uiconfig = {
  "setNavHidden": true,
  "setStatusBarColor": "#00ffffff",
  "setStatusBarUIFlag": 0x00000400,
  "setNumberColor": "#ffffff",
  "setNumberSize": 28,
  "setNumFieldOffsetY": 0,
  "setSloganHidden": true,
  "setLogBtnText": "萌新登录送积分红包",
  "setLogBtnTextColor": '#333333',
  "setLogBtnTextSize": 18,
  "setLogBtnHeight": 48,
  "setLogBtnOffsetY": 0,
  "setLogBtnMarginLeftAndRight": 16,
  "setLogBtnBackgroundPath": "login_btn",
  "setSwitchAccHidden": true,
  "setAppPrivacyOne": "《用户协议》, https://www.baidu.com",
  "setAppPrivacyTwo": "《隐私政策》, https://www.baidu.com",
  "setVendorPrivacyPrefix": "《",
  "setVendorPrivacySuffix": "》",
  "setAppPrivacyColor": "#ffffff,#6491d9",
  "setPrivacyMargin": 56,
  "setProtocolGravity": "LEFT",
  "setPrivacyOffsetY": 0,
  "setCheckboxHidden": false,
  "setCheckBoxWidth": 18,
  "setCheckBoxHeight": 18,
  "setCheckedImgPath": "icon_checked",
  "setUncheckedImgPath": "icon_unchecked",
  "setPageBackgroundPath": "login_background"
};

void main() {
  runApp(App());
}

class App extends StatelessWidget {
  const App({Key key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return MaterialApp(home: MyApp());
  }
}

class MyApp extends StatefulWidget {
  @override
  _MyAppState createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  Map _data;
  Size size;
  @override
  void initState() {
    super.initState();
    uverifyInit();
    Uverify.customClickEventListener((res) {
      print('customClickEventListener===>:${res.toString()}');
      switch (res) {
        case 'otherLogin':
          Uverify.quitLoginPage();
          break;
      }
    });
    Uverify.sdkTokenEventListener((res) {
      print('sdkTokenEventListener===>:${res.toString()}');
      Uverify.hideLoginLoading();
    });
    Uverify.sdkClickEventListener((res) {
      print('sdkClickEventListener===>:${res.toString()}');
      Uverify.hideLoginLoading();
    });

    // 获取设备id
    Uverify.getVerifyId().then((value) {
      print('=getVerifyId==>$value');
    });
  }

  Future<void> addAuthRegistViewConfig() async {
    return Uverify.preLogin().then((res) {
      String carrierName = res['data'];
      print('\$===99==${uiconfig.toString()}==$carrierName');
      uiconfig['setLogBtnOffsetY'] = uiconfig['setSloganOffsetY'] + 48;
      uiconfig['setPrivacyOffsetY'] = uiconfig['setSloganOffsetY'] + 228;
      double averageW = size.width / 3;
      return Uverify.addAuthRegistViewConfig({
        "uiconfig": uiconfig,
        "widgets": [
          {
            "type": 'RelativeLayout',
            'height': 32,
            'width': 32,
            'top': uiconfig['setSloganOffsetY'] + 32,
            'right': 32,
            'backgroundResource': 'login_hbzs_32',
            'layoutGravity': 'RIGHT'
          },
          {
            "widgetId": "otherLogin",
            "type": 'button',
            "text": '其他手机号登录',
            'color': '#66ffffff',
            'fontSize': 18,
            'height': 48,
            'width': -1,
            'left': 16,
            'right': 16,
            'top': uiconfig['setSloganOffsetY'] + 112,
            'backgroundResource': 'login_btn2',
          },
          {
            "type": 'textView',
            "text": '登录即享全场漫画免费看，边看边赚钱',
            'color': '#16ffffff',
            'fontSize': 14,
            'top': uiconfig['setSloganOffsetY'] + 176,
            'layoutGravity': 'CENTER_HORIZONTAL',
          },
          {
            "type": 'textView',
            "text": getCarrierName(carrierName),
            'color': '#ffffff',
            'fontSize': 10,
            'height': 16,
            'width': 70,
            'top': uiconfig['setSloganOffsetY'],
            'layoutGravity': 'CENTER_HORIZONTAL',
            'backgroundResource': 'login_radius'
          },
          {
            "widgetId": "QQ",
            "type": 'button',
            'height': 44,
            'width': 44,
            'left': (averageW - 44) ~/ 2 + 32,
            'top': max(480, (size.height - 144).toInt()),
            'backgroundResource': '@mipmap/qq44',
          },
          {
            "widgetId": "weixin",
            "type": 'button',
            'height': 44,
            'width': 44,
            'top': max(480, (size.height - 144).toInt()),
            'layoutGravity': 'CENTER_HORIZONTAL',
            'backgroundResource': '@mipmap/weixin44',
          },
          {
            "widgetId": "weibo",
            "type": 'button',
            'height': 44,
            'width': 44,
            'left': ((averageW - 44) / 2 + averageW * 2 - 32).toInt(),
            'top': max(480, (size.height - 144).toInt()),
            'backgroundResource': '@mipmap/weibo44',
          }
        ]
      });
    });
  }

  String getCarrierName(code) {
    switch (code) {
      case 'CTCC':
        return '中国电信认证';
      case 'CUCC':
        return '中国联通认证';
      case 'CMCC':
        return '中国移动认证';
      default:
        return '未知认证';
    }
  }

  Future<void> addAuthRegisterXmlConfig() async {
    return Uverify.preLogin().then((res) {
      String carrierName = res['data'];
      print('\$===99==${uiconfig.toString()}==$carrierName');
      uiconfig['setLogBtnOffsetY'] = uiconfig['setSloganOffsetY'] + 48;
      uiconfig['setPrivacyOffsetY'] = uiconfig['setSloganOffsetY'] + 228;
      double averageW = size.width / 3;
      Uverify.addAuthRegisterXmlConfig({
        'uiconfig': uiconfig,
        'xmlconfig': {'layoutResId': '@layout/activity_select'}
      });
    });
  }

  Future<void> getLoginToken() async {
    Map data = await Uverify.getLoginToken({
      "uiconfig": uiconfig,
    });
    setState(() {
      _data = data;
    });
  }

  // Platform messages are asynchronous, so we initialize in an async method.
  Future<void> uverifyInit() async {
    Map data;
    // Platform messages may fail, so we use a try/catch PlatformException.
    try {
      Uverify.init(
          appKey: UmengConfig.appKey, //"你自己应用的 AppKey",
          appSecret: UmengConfig.appSecret //"你自己应用的 AppKey",
          );
    } on PlatformException {
      // data = 'Failed to get platform version.';
    }

    // If the widget was removed from the tree while the asynchronous platform
    // message was in flight, we want to discard the reply rather than calling
    // setState to update our non-existent appearance.
    if (!mounted) return;

    setState(() {
      _data = data;
    });
  }

  @override
  Widget build(BuildContext context) {
    // size = MediaQuery.of(context).size;
    // int y = (size.width * (8 / 15)).toInt();
    int y = 300;
    uiconfig['setNumFieldOffsetY'] = y - 70;
    uiconfig['setSloganOffsetY'] = y - 30;
    return MaterialApp(
        home: Scaffold(
      appBar: AppBar(
        title: const Text('Plugin example app'),
      ),
      body: Container(
          child: Column(children: [
        Center(
          child: Text('Running s on: ${_data.toString()}\n'),
        ),
        OutlineButton(
          padding: EdgeInsets.all(0),
          onPressed: () {
            getLoginToken();
          },
          child: Text('默认授权登录'),
        ),
        OutlineButton(
          padding: EdgeInsets.all(0),
          onPressed: () {
            addAuthRegistViewConfig();
          },
          child: Text('自定义UI'),
        ),
        OutlineButton(
          padding: EdgeInsets.all(0),
          onPressed: () {
            addAuthRegisterXmlConfig();
          },
          child: Text('自定义XMLUI'),
        )
      ])),
    ));
  }
}
